--[[
	Project....: LUI NextGenWoWUserInterface - LUITracker Module
	File.......: luitracker.lua
	Description: Inventory Tracker Module
	Version....: 1.0
	Rev Date...: 29/11/2010
]]
local LUI = LibStub("AceAddon-3.0"):GetAddon("LUI")
local LSM = LibStub("LibSharedMedia-3.0")
local widgetLists = AceGUIWidgetLSMlists
local LUIHook = LUI:GetModule("LUIHook")
local module = LUI:NewModule("LUITracker", "AceHook-3.0");

local db

local GetItemInfo, UnitName, pairs, tinsert, GetContainerNumSlots, GetContainerItemInfo = GetItemInfo, UnitName, pairs, tinsert, GetContainerNumSlots, GetContainerItemInfo;

local myTooltip = nil;

local defaults = {
	LUITracker = {
		Enable = true,
		Inventory = { },
		Bank = { }
	}
};

local altProfiles = { }
local item_list = { }
local bank_list = { }

local item_cache = { }

function module:LoadOptions()
	local options = {
		LUITracker = {
			name = "Inventory Tracker",
			type = "group",
			order = 60,
			disabled = function() return not db.LUITracker.Enable; end,
			childGroups = "select",
			args = {
				empty1 = {
					name = " \n ",
					width = "full",
					type = "description",
					order = 1
				},
				desc = {
					name = "|cff3399ffNotice:|r\nOptions will be added later.",
					width = "full",
					type = "description",
					order = 2
				}
			}
		}
	};
	return options
end

function module:LoadModule()
	local module = {
		LUITracker = {
			order = LUI:GetModuleCount(),
			type = "execute",
			name = function()
				if (db.LUITracker.Enable) then
					return "|cff00ff00Inventory Tracker Enabled|r";
				else
					return "|cffFF0000Inventory Tracker Disabled|r";
				end
			end,
			func = function(self, BW)
				db.LUITracker.Enable = not db.LUITracker.Enable;
				StaticPopup_Show("RELOAD_UI");
			end
		}
	};
	return module;
end

function module:OnInitialize()
	LUI:MergeDefaults(LUI.db.defaults.profile, defaults);
	LUI:RefreshDefaults();
	LUI:Refresh();
	self.db = LUI.db;
	db = self.db.profile;
end

function module:OnEnable()
	LUI:RegisterOptions(module:LoadOptions());
	LUI:RegisterModule(module:LoadModule());
	if (db.LUITracker.Enable) then
		module:CreateMainFrame();
	end
end

function module:UpdateBags(bags, typ)
	local tbl = nil;
	
	if (typ == "bank") then
		bank_list = { };
		tbl = bank_list;
	elseif (typ == "items") then
		item_list = { };
		tbl = item_list;
	end
	for _, i in pairs(bags) do
		local bag_count = GetContainerNumSlots(i);
		if (bag_count > 0) then
			for j = 1, bag_count do
				local itemID = GetContainerItemID(i, j);
				if (itemID) then
					local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount, itemEquipLoc, itemTexture, itemSellPrice = GetItemInfo(itemID);
					local texture, count, locked, quality = GetContainerItemInfo(i, j);
					item = { 
						["name"] = itemName,
						["link"] = itemLink,
						["rarity"] = itemRarity,
						["ilevel"] = itemLevel,
						["level"] = itemMinLevel,
						["type"] = itemType,
						["subtype"] = itemSubType,
						["stack"] = itemStackCount,
						["equip"] = itemEquipLoc,
						["texture"] = itemTexture,
						["sell"] = itemSellPrice,
						["count"] = count,
						["locked"] = locked
					};
					tinsert(tbl, #tbl+1, item);
				end
			end
		end
	end
end

function module:UNIT_INVENTORY_CHANGED(unit)
	module:UpdateBags({0,1,2,3,4}, "items");
end
function module:BANKFRAME_OPENED(self, ...)
	local bags = { -1, 5, 6, 7, 8, 9, 10, 11 };
	
	module:UpdateBags(bags, "bank");
	print("    "..#bank_list.." items in bank.");
end

function module:SetItem(...)
	local found = false;
	local who = {};
	local itemName, itemLink = GameTooltip:GetItem();
	if (itemName) then
		if (item_cache[itemName]) then
			who = item_cache[itemName];
			found = true;
		else
			for i,v in pairs(module.profiles) do
				if (i ~= UnitName("player")) then
					if (v.LUITracker and v.LUITracker.Inventory) then
						for _,j in pairs(v.LUITracker.Inventory) do
							if (j.link == itemLink) then
								found = true;
								tinsert(who, #who + 1, { name = i, count = j.count});
							end
						end
					end
				end
			end
		end
		if (found) then
			myTooltip:Hide();
			myTooltip:SetOwner(self, "ANCHOR_TOPLEFT");
			for i,v in pairs(who) do
				myTooltip:AddLine(string.format("%-12s: %d", v.name, v.count), 1, 1, 1, 1);
			end
			myTooltip:SetWidth(GameTooltip:GetWidth());
			myTooltip:SetPoint("RIGHT", GameTooltip, "RIGHT", 0, 0);
			myTooltip:Show();
			GameTooltip:Show();
			item_cache[itemName] = who;
		end
	end
end
function module:TooltipCleared(...)
	-- Clear any storage?
	myTooltip:ClearLines();
	myTooltip:Hide();
end

function module:OnSizeChanged(...)
end
function module:CreateMainFrame()
	-- We will first get a listing of inventory.
	module:UpdateBags({0, 1, 2, 3, 4 }, "items");
	local f = CreateFrame("Frame");
	f:RegisterEvent("BANKFRAME_OPENED");
	f:RegisterEvent("UNIT_INVENTORY_CHANGED");
	f:SetScript("OnEvent", function(this, event, ...) module[event](self, ...) end);
	print("LUITracker loaded.");
	print("    " .. #item_list .. " items in inventory.");
	db.LUITracker.Inventory = item_list;
	GameTooltip:HookScript("OnTooltipSetItem", module.SetItem);
	GameTooltip:HookScript("OnTooltipCleared", module.TooltipCleared);
	GameTooltip:HookScript("OnSizeChanged", module.OnSizeChanged);
	myTooltip = CreateFrame("GameTooltip", "LUITracker_GameTooltip", UIParent, "GameTooltipTemplate");
	myTooltip:SetBackdrop({
		bgFile = "Interface/Tooltips/ChatBubble-Background",
		edgeFile = "Interface/Tooltips/ChatBubble-BackDrop",
		tile = true, tileSize = 32, edgeSize = 32,
		insets = { left = 32, right = 32, top = 32, bottom = 32 }
	});
	myTooltip:SetBackdropColor(0,0,0.3, 1)
	myTooltip:SetClampedToScreen(true)
	module.profiles = LUI.db.sv.profiles;
end